// ============================== 导入依赖 ============================== //

import CORE from '@/CORE'

const GAP = 10 // 间隔分钟数
const COUNT = 1440 / GAP | 0 + 1 // 总个数

const HALF_HOUR = 1800000

// ============================== 导出状态集 ============================== //

export default {
  /**
   * 获取图片
   */
  getImg: (name) => CORE.common(`monitor/elec/${name}.png`),

  /**
   * 获取名称列表
   */
  getNames: () => Array(COUNT).fill().map((_, i) => transName(i)),

  /**
   * 转换数据列表
   */
  transDataList(obj, days = 0) {
    const keys = Object.keys(obj || {})
    const dataList = Array(COUNT).fill(0)
    const begin = CORE.timeNum(CORE.today(days)) - GAP * 30000 // 该天往前 5 分钟的时间戳

    keys.forEach((key) => {
      const index = (+key - begin) / 60000 / GAP | 0
      if (index >= 0 && index < COUNT) dataList[index] += obj[key]
    })

    return dataList
  },

  /**
   * 转换记录列表
   */
  transRecordList(list = []) {
    list.forEach((item) => {
      item.date = CORE.timeStr(item.collectTime).slice(0, -3)
      item.time = item.date.slice(11)
    })
    return list.reverse()
  },

  /**
   * 转换整点列表 (将最接近整点的行数摘出来，结果为 15 行)
   */
  transHourList(list = [], beginTime) {
    const xData = Array(25).fill().map((_, i) => beginTime + i * HALF_HOUR * 2)
    const secondArrList = xData.map(() => [])
    const iArrList = xData.map(() => [])
    list.forEach((item, i) => {
      const index = xData.findIndex((time) => Math.abs(time - item.collectTime) <= HALF_HOUR)
      if (index >= 0) {
        secondArrList[index].push(Math.abs(xData[index] - item.collectTime))
        iArrList[index].push(i)
      }
    })
    return xData.map((x, i) => {
      const min = Math.min(secondArrList[i])
      const minIndex = secondArrList[i].findIndex((second) => second === min)
      const itemIndex = iArrList[i][minIndex]
      const item = list[itemIndex]
      const date = CORE.timeStr(x).slice(0, -3)
      const time = date.slice(11)
      return { ...item, date, time }
    })
  },

  /**
   * 转换字段列表
   */
  transFieldList(list = [], FIELD_DICT = []) {
    return list.map((row) => {
      const data = { id: row.id, time: row.time }
      FIELD_DICT.forEach(([name, field, unit = '']) => {
        const value = name ? CORE.isNumber(row[field]) ? row[field] : '-' : ''
        data[field] = `${value}${unit}`
      })
      return data
    })
  },
}

// ============================== 转换方法 ============================== //

const transName = (i) => {
  const minutes = i * GAP
  const minuteStr = `0${minutes % 60}`.slice(-2)
  const hourStr = `0${(minutes - minutes % 60) / 60}`.slice(-2)
  return `${hourStr}:${minuteStr}`
}
